import koaJwt from 'koa-jwt';
import type { Context } from 'koa';
import { decodeToken } from '@/helpers/tokenVerify';
import { jwtWhitePaths } from '@/configs/router.conf';

const secret = process.env.ACCESS_TOEN_SECRET;

const getToken = (ctx: Context) => {
  let token = ctx.header.authorization;
  if (token) {
    token = token.replace(/Bearer /, '');
    const res = decodeToken(token);
    ctx.userId = res?.userId;
  }
  return token;
}

export const jwtMiddleware = () => {
  return koaJwt({ secret, getToken }).unless({ 
    path: jwtWhitePaths 
  });
}